package com.example.status;

import com.example.model.WaterSensor;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.api.common.typeinfo.Types;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.util.Collector;

import java.time.Duration;

/**
 * Created with IntelliJ IDEA.
 * ClassName: ValueDemo
 * Package: com.example.status
 * Description:
 * User: fzykd
 *
 * @Author: LQH
 * Date: 2023-07-26
 * Time: 10:39
 */

public class ValueDemo {
    public static void main(String[] args) throws Exception {

        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

        env.setParallelism(1);

        final SingleOutputStreamOperator<WaterSensor> data = env.socketTextStream("hadoop102", 7777)
                .map(new MapFunction<String, WaterSensor>() {
                    @Override
                    public WaterSensor map(String value) throws Exception {
                        final String[] s = value.split(" ");

                        return new WaterSensor(s[0], Long.valueOf(s[1]), Integer.valueOf(s[2]));
                    }
                })
                //设置水位线 和 分配策略
                .assignTimestampsAndWatermarks(
                        WatermarkStrategy
                                //乱序水位线 设置为3秒
                                .<WaterSensor>forBoundedOutOfOrderness(Duration.ofSeconds(3))
                                .withTimestampAssigner((val, ts) -> val.getTs() * 1000L)
                );

        //需求 检测每种传感器的水位值 如果连续两个水位值超过10 就输出报价
        // 每种 说明 要分区 keyBy
        data.keyBy(value -> value.getId())
                //需求没有直接使用的算子 就用最底层的process
                .process(new KeyedProcessFunction<String, WaterSensor, String>() {

                    //如果定义普通变量
                    ValueState<Integer> lastVc;

                    @Override
                    public void open(Configuration parameters) throws Exception {
                        //状态的初始化 一定要在open方法当中
                        lastVc = getRuntimeContext().
                                //从运行时上下文中获取状态 参数是一个状态描述器 参数是 状态名字 和 类型 （因为一个算子可以定义多个状态）
                                        getState(new ValueStateDescriptor<Integer>("lastVc", Types.INT));
                    }

                    @Override
                    public void processElement(WaterSensor value, Context ctx, Collector<String> out) throws Exception {

                        //连续的 说明 来的数据要和上一条比较
                        //1.取出上一条的水位值 如果是第一条数据值 Integer 默认值是null
                        int val = lastVc.value() == null ? 0 : lastVc.value(); //取出值状态的值
                        //最差 绝对值
                        if (Math.abs(value.getVc() - val) > 10) {
                            out.collect( "传感器ID = " +value.getId() +" 当前水位值 = " + value.getVc() + " 与上一条水位值 = " + val + " 相差超过10 ！！！");
                        }
                        //更新状态
                        lastVc.update(value.getVc());
                    }
                }).print();


        env.execute();

    }
}
